package com.example.taobaou.presenter.impl;

import android.util.Log;

import com.example.taobaou.model.Api;
import com.example.taobaou.model.domain.Categories;
import com.example.taobaou.presenter.IHomePresenter;
import com.example.taobaou.utils.RetrofitManager;
import com.example.taobaou.view.IHomeCallback;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class HomePresenterImpl implements IHomePresenter {


    private IHomeCallback mCallback = null;

    @Override
    public void getCategories() {
        if (mCallback != null) {
            mCallback.onLoading();
        }
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api  api = retrofit.create(Api.class);
        final Call<Categories> task = api.getCatrgories();
        task.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                //数据结果
                int code = response.code();
//                Log.d(TAG, "code is -->"+code);
                if (code == HttpURLConnection.HTTP_OK){
                    //请求成功
                    Categories categorys = response.body();
//                    Log.d(TAG, categorys.toString());
                    if (mCallback != null){
                        if (categorys == null || categorys.getData().size() == 0) {
                            mCallback.onEmpty();
                        }else {
                            mCallback.onCategoriesLoaded(categorys);
                        }
                    }
                }else {
                    //请求失败
//                    Log.d(TAG, "请求失败........01");
                    if (mCallback != null) {
                        mCallback.onNatworkError();
                    }
                }
            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                //加载失败的结果
                Log.d(TAG, "请求失败........02"+t);
                if (mCallback != null) {
                    mCallback.onNatworkError();
                }
            }
        });

    }



    @Override
    public void registerViewCallback(IHomeCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void unregisiterViewCallback(IHomeCallback callback) {
        mCallback = null;
    }
}
